//
//  ViewController2.m
//  NSNotificationCenterDemo
//
//  Created by mobao on 16/4/6.
//  Copyright © 2016年 mobao. All rights reserved.
//

#import "ViewController2.h"

@interface ViewController2(){
    
}
@end

@implementation ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //添加观察者1
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationSel:) name:@"NOTIFICATION_NAME1" object:nil];
    
    //添加观察者2
    self.observer = [[NSNotificationCenter defaultCenter]addObserverForName:@"NOTIFICATION_NAME2" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        NSDictionary *dic = note.userInfo;
        
        NSString *string = [dic objectForKey:@"key"];
        
        NSLog(@"通知已接收，传递的对象2是：%@",string);
        
    }];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    //移除观察者1
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"NOTIFICATION_NAME1" object:nil];
    
    
    
    //移除观察者2
    //可以看出移除方式与第一种观察者有着明显区别：
    if (self.observer) {
        
        [[NSNotificationCenter defaultCenter]removeObserver:self.observer];
        
        //最后的observer一定要置为nil，否则观察者一定不会被移除
        self.observer = nil;
        
    }
}

//响应事件
-(void)notificationSel:(NSNotification*)not{
    
    NSDictionary *dic = not.userInfo;
    
    NSString *string = [dic objectForKey:@"key"];
    
    NSLog(@"通知已接收，传递的对象1是：%@",string);
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
